<div id="formDiv"></div>
<script type="text/html" id="warehouseProductionOrderformContent">
  <form lay-filter="warehouseProductionOrderForm" id="warehouseProductionOrderForm" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <div>
          <div class="layui-form-item layui-row">
            <input name="id" type="hidden" />
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">选择客户</label>

              <div class="layui-input-block">
                <select id="customerId" name="customerId" lay-filter="customerId"></select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label"> 所属生产订单</label>
              <input  name="productionOrderNumber" type="hidden" />
              <div class="layui-input-block">
                <select id="productionOrderId" name="productionOrderId" lay-filter="productionOrderId"></select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">选择产品</label>
              <input  name="productSpecCode" type="hidden" />
              <input  name="productCode" type="hidden" />
              <input  name="productionOrderDetailId" type="hidden" />
              <div class="layui-input-block">
                <select id="productId" name="productId" lay-filter="productId"></select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">计划交货时间</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" id="plannedDeliveryTime" name="plannedDeliveryTime" />
              </div>
            </div>


          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">品种</label>
              <input  name="productVarietyId" type="hidden" />
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productVariety" disabled name="productVariety" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">	规格</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productSpecCode" disabled name="productSpecCode" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <input class="layui-input adv-disable" type="hidden" id="remainingProductionSchedule" disabled name="remainingProductionSchedule" />
              <label class="layui-form-label">需求数</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="requiredQuantity" disabled name="requiredQuantity" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">剩余排产数量</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="scheduleQuantity" disabled name="scheduleQuantity" />
              </div>
            </div>
          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">厚度/壁厚/直径</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input " id="diameter" disabled name="diameter" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">宽度/外径</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" id="width" disabled name="width" />
              </div>
            </div> <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">长度</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" id="length" disabled name="length" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">备注</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" id="remark" name="remark" />
              </div>
            </div>

          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">图纸</label>
              <div class="layui-input-block">
                <input type="hidden" class="layui-input adv-disable" id="processingDrawing" disabled name="processingDrawing" />
                <button class="layui-btn layui-btn-sm" id="processingDrawingBtn" type="button">
                  查看附件
                </button>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">材料料号</label>
              <div class="layui-input-block">
                <button class="layui-btn layui-btn-sm" id="materialDetail" type="button">无物料</button>
                <input  class="layui-input" type="hidden" id="materialNumber" name="materialNumber" />
              </div>
            </div>
            <!-- <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">计划生产数量</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" disabled name="plannedQuantity" />
              </div>
            </div> -->


           </div>
        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName !== 'detail'){ }} -->
          <button class="layui-btn" type="button" id="Configure">添加排产信息</button>
          <!-- {{# } }} -->
          <table class="layui-table" id="purchasePlanFormTable" lay-filter="purchasePlanFormTable"></table>
        </div>

        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
          <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
        </div>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="purchasePlanFormTableBar">
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del"
    type="button"
  >
    删除
  </button>
</script>
<script type="text/html" id="customerSku">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <button class="layui-btn " id="addCustomerSku">确认选择</button>
        <table class="layui-table" id="customerSkuTable"></table>
      </div>
    </div>
  </div>
</script>
<script type="text/html" id="warehouseMaterialRequisitionRecordForm">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <table
          class="layui-table"
          id="warehouseMaterialRequisitionRecordTable"
          lay-filter="warehouseMaterialRequisitionRecordTable"
        ></table>
      </div>
    </div>
  </div>
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };
      let data = nowData?.data;
      let skuList = [];

      laytpl(warehouseProductionOrderformContent.innerHTML).render(
        { ...nowData },
        function (html) {
          $("#formDiv").after(html);
        }
      );
      // 初始化日期选择
      laydate.render({
        elem: "#plannedDeliveryTime",
        type: "datetime",
      });

      // 初始化客户选择
      await admin.initDataSelectPro(
        "enterprise/sell/admin/customersInfo/list",
        { limit: 99999 },
        "customerId",
        "客户名称",
        async (d) => {
          $("#contractId").empty();
          $("#contractId").val("");
          $("#productionOrderId").empty();
          $("#productionOrderId").val("");
          if (d.value) {
            await admin.initDataSelectPro(
              "warehouse/warehouse/productionOrder/list",
              {
                customerId: d.value,
              },
              "productionOrderId",
              "生产订单编号",
              async (d, obj) => {
                $("#productId").empty();
                form.val("warehouseProductionOrderForm", {
                  productVarietyId: "",
                  productSpecCode: "",
                  requiredQuantity: "",
                  diameter: "",
                  width: "",
                  length: "",
                  materialNumber: "",
                  processingDrawing: "",
                  productVariety: "",
                  remark: "",
                  productionOrderNumber: "",
                  productId: "",
                });
                if (d.value) {
                  // obj.id ? delete obj.id : "";
                  form.val("warehouseProductionOrderForm", {
                    productionOrderNumber: obj.productionOrderNumber,
                    remainingProductionSchedule:
                      obj.remainingProductionSchedule,
                  });
                  const { data } = await admin.reqPro(
                    "warehouse/warehouse/productionOrder/selectProductionDetail",
                    { id: d.value }
                  );
                  // 过滤掉剩余排产数量为0的
                  let list = data.warehouseProductionOrderDetailList.filter(
                    (v) => v.scheduleQuantity != 0
                  );
                  admin.initDataSelect(
                    list,
                    {},
                    "productId",
                    null,
                    "产品名称",
                    "productCode",
                    "productId"
                  );
                  form.on("select(productId)", function (d) {
                    form.val("warehouseProductionOrderForm", {
                      productVarietyId: "",
                      productSpecCode: "",
                      requiredQuantity: "",
                      diameter: "",
                      width: "",
                      length: "",
                      materialNumber: "",
                      processingDrawing: "",
                      productVariety: "",
                      remark: "",
                      productionOrderDetailId: "",
                    });
                    let obj = data.warehouseProductionOrderDetailList.find(
                      (v) => v.productId == d.value
                    );
                    obj.productionOrderDetailId = obj.id;
                    delete obj.id;
                    form.val("warehouseProductionOrderForm", { ...obj });
                    $("#materialDetail").text(
                      obj.materialNumber ? obj.materialNumber : "无物料"
                    );
                    console.log(obj);
                  });
                }
              },
              "productionOrderNumber"
            );
          }
        },
        "customerName"
      );
      const workshopData = await admin.reqPro(
        "enterprise/device/admin/deviceWorkshop/list",
        {}
      );
      const workshopList = workshopData.data.map((v) => {
        return {
          label: v.name,
          value: v.id,
        };
      });
      const productionLineData = await admin.reqPro(
        "warehouse/warehouse/productionLine/list",
        {}
      );
      const productionLineList = productionLineData.data.map((v) => {
        return {
          label: v.workshopName,
          value: v.id,
          workshopId: v.workshopId,
        };
      });
      if (nowData.eventName === "detail") {
        admin.setFormDisable("#warehouseProductionOrderForm", true);
      }

      const tableVal = table.render({
        elem: "#purchasePlanFormTable",
        page: false,
        limit: 999999,
        height: 400,
        data: [],
        cols: [
          [
            { type: "numbers", title: "序号" },
            {
              field: "workshopId",
              title: "选择车间",
              templet: admin.setTableSelect(
                "workshopId",
                workshopList,
                nowData.eventName == "detail",
                "workshopId"
              ),
            },
            {
              field: "productionLineId",
              title: "选择产线",
              templet: function (d) {
                if (d.workshopId) {
                  return admin.setTableSelect(
                    "productionLineId",
                    productionLineList.filter(
                      (v) => v.workshopId == d.workshopId
                    ),
                    nowData.eventName == "detail"
                  )(d);
                } else {
                  return "请选择车间";
                }
              },
            },
            {
              field: "plannedProductionTime",
              title: "计划生产时间",
              templet: function (d) {
                return admin.setTableInput(
                  "plannedProductionTime",
                  nowData.eventName == "detail",
                  "plannedProductionTime" + d.LAY_TABLE_INDEX
                )(d);
              },
            },
            {
              field: "plannedQuantity",
              title: "计划生产数量",
              templet: admin.setTableInput(
                "plannedQuantity",
                nowData.eventName == "detail",
                "plannedQuantity"
              ),
            },
            {
              field: "remark",
              title: "备注信息",
              templet: admin.setTableInput(
                "remark",
                nowData.eventName == "detail",
                "remark"
              ),
            },
            { title: "操作", toolbar: "#purchasePlanFormTableBar" },
          ],
        ],
        done: function (tableData) {
          admin.tableInputChange("purchasePlanFormTable");
          admin.tableInputChangeByClass(
            "purchasePlanFormTable",
            "plannedQuantity"
          );
          admin.tableInputChangeByClass("purchasePlanFormTable", "remark");
          admin.tableSelectChange(
            "purchasePlanFormTable",
            "workshopId",
            (index, value, tableData, field, tableId) => {
              tableVal.reload({
                data: tableData,
              });
            }
          );
          tableData.data.forEach((v) => {
            laydate.render({
              elem: ".plannedProductionTime" + v.LAY_TABLE_INDEX,
              type: "datetime",
              done: function (value, date, endDate) {
                v.plannedProductionTime = value;
              },
            });
          });
        },
      });

      if (data && data.id) {
        await admin.initDataSelectPro(
          "warehouse/warehouse/productionOrder/list",
          {
            customerId: data.customerId,
          },
          "productionOrderId",
          "生产订单编号",
          async (d, obj) => {
            $("#productId").empty();
            form.val("warehouseProductionOrderForm", {
              productionOrderNumber: "",
              productId: "",
            });
            if (d.value) {
              delete obj.id;
              form.val("warehouseProductionOrderForm", {
                productionOrderNumber: obj.productionOrderNumber,
              });

              const { data } = await admin.reqPro(
                "warehouse/warehouse/productionOrder/selectProductionDetail",
                { id: d.value }
              );
              admin.initDataSelect(
                data.warehouseProductionOrderDetailList,
                {},
                "productId",
                null,
                "产品名称",
                "productCode",
                "productId"
              );
              form.on("select(productId)", function (d) {
                let obj = data.warehouseProductionOrderDetailList.find(
                  (v) => v.productId == d.value
                );
                delete obj.id;

                form.val("warehouseProductionOrderForm", obj);
              });
            }
          },
          "productionOrderNumber"
        );
        const res = await admin.reqPro(
          "warehouse/warehouse/productionOrder/selectProductionDetail",
          { id: data.productionOrderId }
        );
        admin.initDataSelect(
          res.data.warehouseProductionOrderDetailList,
          {},
          "productId",
          data.productId,
          "产品名称",
          "productCode",
          "productId"
        );

        form.val("warehouseProductionOrderForm", data);
        $("#materialDetail").text(
          data.materialNumber ? data.materialNumber : "无物料"
        );
        // 生产计划详情和制造令详情公用一个  区别有无productId
        console.log(
          "nowData.productId",
          data.warehouseProductionSchedulingPlanDetailList.filter(
            (v) => v.id == nowData.productId
          )
        );

        if (nowData.productId) {
          tableVal.reload({
            data: data.warehouseProductionSchedulingPlanDetailList.filter(
              (v) => v.id == nowData.productId
            ),
          });
        } else {
          tableVal.reload({
            data: data.warehouseProductionSchedulingPlanDetailList,
          });
        }
      } else {
        tableVal.reload({
          data: [
            {
              workshopId: "",
              productionLineId: "",
              plannedProductionTime: "",
              plannedQuantity: "",
              remark: "",
            },
          ],
        });
      }

      form.on("submit(formSubmit)", function (d) {
        let formData = { ...d.field };
        // 需求数要求数字类型
        formData.requiredQuantity = Number(formData.requiredQuantity);
        formData.scheduleQuantity = Number(formData.scheduleQuantity);
        formData.remainingProductionSchedule = Number(
          formData.remainingProductionSchedule
        );
        formData.productionOrderDetailId = Number(
          formData.productionOrderDetailId
        );
        formData.warehouseProductionSchedulingPlanDetailList = table.cache[
          "purchasePlanFormTable"
        ].map((v) => {
          v.plannedQuantity = Number(v.plannedQuantity);
          v.workshopName = workshopList.find(
            (v1) => v1.value == v.workshopId
          )?.label; // 车间名称
          v.productionLineName = productionLineList.find(
            (v1) => v1.value == v.productionLineId
          )?.label; // 产线名称
          return v;
        });
        if (
          formData.warehouseProductionSchedulingPlanDetailList.some(
            (v) => v.workshopId == "" && v.productionLineId == ""
          )
        ) {
          layer.msg("请完善表格数据");
          return false;
        }
        formData.plannedQuantity =
          formData.warehouseProductionSchedulingPlanDetailList.reduce(
            (v, c) => v + Number(c.plannedQuantity),
            0
          );
        if (formData.plannedQuantity > formData.scheduleQuantity) {
          // 弹框确认是否继续
          layer.confirm(
            "计划生产数量大于需求数，是否继续",
            { icon: 3, title: "提示" },
            function (index) {
              submitForm(formData);
            }
          );
        } else {
          submitForm(formData);
        }

        return false;
      });
      function submitForm(formData) {
        if (nowData.eventName == "add") {
          delete formData.id;
          admin.req(
            "warehouse/warehouse/productionSchedulingPlan/add",
            JSON.stringify(formData),
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                table.reload("ProductionOrderTable");
                layer.closeAll("page");
              } else {
                layer.msg(res.msg, { icon: 2, time: 1000 });
              }
            },
            "POST",
            false,
            "application/json"
          );
        } else if (nowData.eventName == "edit") {
          admin.req(
            "warehouse/warehouse/productionSchedulingPlan/update",
            JSON.stringify(formData),
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                table.reload("ProductionOrderTable");
                layer.closeAll("page");
              } else {
                layer.msg(res.msg, { icon: 2, time: 1000 });
              }
            },
            "POST",
            false,
            "application/json"
          );
        }
      }
      table.on("tool(purchasePlanFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["purchasePlanFormTable"].filter((v) => {
            return v["LAY_TABLE_INDEX"] != index;
          });
          table.reload("purchasePlanFormTable", {
            data: list,
          });
        }
      });
      $("#Configure").click(function () {
        if (
          table.cache["purchasePlanFormTable"].some(
            (v) => v.workshopId == "" && v.productionLineId == ""
          )
        ) {
          layer.msg("请完善表格数据");
        } else {
          table.cache["purchasePlanFormTable"].push({
            workshopId: "",
            productionLineId: "",
            plannedProductionTime: "",
            plannedQuantity: "",
            remark: "",
          });
          tableVal.reload({
            data: table.cache["purchasePlanFormTable"],
          });
        }
      });
      // $("#materialDetail").click(function () {
      //   if ($("#materialNumber").val()) {
      //     let zindex = admin.formOpen({
      //       area: "90%",
      //       offset: "10%",
      //       title: "物料详情",
      //       content: $("#warehouseMaterialRequisitionRecordForm").html(),
      //       success: function () {
      //         // if (nowData.eventName === "detail") {
      //         //   admin.setFormDisable("#warehouseMaterialRequisitionRecordForm", true);
      //         // }
      //         // parentData.list = d.materialNumber;
      //         admin.req(
      //           "warehouse/warehouse/product/list",
      //           {
      //             limit: 999999,
      //             productIds: $("#materialNumber").val().split(",")
      //           },
      //           (res) => {
      //             table.render({
      //               elem: "#warehouseMaterialRequisitionRecordTable",
      //               // url: config.base + "warehouse/warehouse/product/list",
      //               data: res.data,
      //               page: false,
      //               cols: [
      //                 [
      //                   { field: "productVariety", align: "center", title: "品种" },
      //                   { field: "productCode", align: "center", title: "客户成品料号" },
      //                   { field: "productSpecCode", align: "center", title: "规格" },
      //                   { field: "diameter", align: "center", title: "厚度/壁厚/直径" },
      //                   { field: "width", align: "center", title: "宽度/外径" },
      //                   { field: "length", align: "center", title: "长度" },
      //                   { field: "productMainUnit", align: "center", title: "成品单位" }
      //                 ]
      //               ]
      //             });
      //           }
      //         );
      //       }
      //     });
      //   } else {
      //     layer.msg("当前产品未配置材料");
      //   }
      // });

      $("#processingDrawingBtn").click(function () {
        if ($("#processingDrawing").val()) {
          window.open($("#processingDrawing").val(), "_blank");
        } else {
          layer.msg("当前产品未配置图纸");
        }
      });
      $("#warehouseProductionOrderForm .layui-table-body").css(
        "overflow",
        "visible"
      );
      $("#warehouseProductionOrderForm .layui-table-box").css(
        "overflow",
        "visible"
      );
      $("#warehouseProductionOrderForm .layui-table-view").css(
        "overflow",
        "visible"
      );
    }
  );
</script>

<style>
  #warehouseProductionOrderForm .layui-form-label {
    width: 125px;
  }

  #warehouseProductionOrderForm .layui-input-block {
    margin-left: 155px;
  }

  #warehouseProductionOrderForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
  #warehouseProductionOrderForm .layui-table-cell {
    overflow: visible !important;
  }
</style>
